package main

import (
	"encoding/json"
	"fmt"
	"go_code/project01_basic/chapter15_qq/message"
	"go_code/project01_basic/chapter15_qq/server/processes"
	"go_code/project01_basic/chapter15_qq/server/utils"
	"io"
	"net"
)

type Processor struct {
	Conn net.Conn
}

func (p *Processor) processing() (err error) {
	for {
		tf := &utils.Transfer{
			Conn: p.Conn,
		}
		fmt.Println("读取客户端数据...")
		mes, err := tf.ReadPkg()
		if err == io.EOF {
			fmt.Println("客户端退出,服务器端也退出...")
			return err
		} else if err != nil {
			fmt.Println("readPkg err=", err)
			return err
		}
		err = p.serverProcessMes(mes)
		if err != nil {
			fmt.Println("消息服务err:", err)
			return err
		}
	}
}

func (p *Processor) serverProcessMes(mes *message.Message) (err error) {
	switch mes.Type {
	case message.LoginMesType:
		up := &processes.UserProcess{
			Conn: p.Conn,
		}
		err = up.SeverProcessLogin(mes)
	case message.RegisterMesType:
		up := &processes.UserProcess{
			Conn: p.Conn,
		}
		err = up.SeverProcessRegister(mes)
	case message.OfflineMesType:
		up := &processes.UserProcess{
			Conn: p.Conn,
		}
		err = up.ServerProcessOffline(mes)
	case message.SmsMesType:
		s := &processes.SmsProcess{}
		err = s.SeverProcessGroupSms(mes)
	case message.SmsPrivateMesType:
		s := &processes.SmsProcess{}
		err = s.SeverProcessPrivateSms(mes)
	case message.FileMesType:
		up := &processes.UserProcess{
			Conn: p.Conn,
		}
		fileMes := &message.FileMes{}
		err = json.Unmarshal([]byte(mes.Data), fileMes)
		if err != nil {
			fmt.Println("json.Unmarshal err=", err)
			return
		}
		err = up.SeverProcessFileMes(fileMes)
	case message.FileResMesType:
		var fileResMes message.FileResMes
		err = json.Unmarshal([]byte(mes.Data), &fileResMes)
		if err != nil {
			fmt.Println("json.Unmarshal err=", err)
			return
		}
		if fileResMes.Res == message.FileReceive {
			up := &processes.UserProcess{
				Conn: p.Conn,
			}
			err = up.SendFile(fileResMes.FileName)
		}
	default:
		fmt.Println("[server]消息类型不存在,无法处理.")
	}
	return
}
